package com.wushijia.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * description:使用EnableWebSecurity注解开启权限验证，并做相关配置
 *
 * @author yang
 * @date 2018/11/13 10:21
 */
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Override
  @Bean
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }

  @Override
  @Bean
  public UserDetailsService userDetailsServiceBean() throws Exception {
    return super.userDetailsServiceBean();
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //spring boot2.x配置，需加入PasswordEncoder的实例
    auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
        .withUser("user001")
        .password("pwd001")
        .roles("USER")
        .and()
        .withUser("admin")
        .password("pwdAdmin")
        .roles("USER", "ADMIN");
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests()
        .anyRequest().authenticated()
        .and().logout().permitAll()//注销
        //.and().formLogin().loginPage("/login").permitAll()//表单登录不用拦截，如果权限不足，会跳转到登录页：域名+端口/login，可自定义登录页
        .and().httpBasic();
  }
}
